<?php
    header("Content-type:text/html;charset=utf-8");
    require('./conn/mysql.php');

    $type = $_POST['type'];

    try{
        if('add' == $type){
            $list = $_POST['data'];
            $arr = json_decode($list, true);
            foreach ($arr as $key => $value) {
                if(is_array($value)){
                    $value['add_time'] = date('Y-m-d H:i:s', time());
                    
                    $res = mysql::exec('cart', $value, 'insert');
                    if(!$res) die(write(0, '添加失败!'));
                }
            }

            echo write(1, '添加成功!');
        }else if('edit' == $type){
            $list = $_POST['data'];
            $arr = json_decode($list, true);
            foreach ($arr as $key => $value) {
                if(is_array($value)){
                    $cart_id = $value['cart_id'];
                    unset($value['cart_id']);
                    $user_id = $value['user_id'];
                    unset($value['user_id']);
                    
                    $res = mysql::exec('cart', $value, 'update', '`cart_id`='.$cart_id.' and `user_id`='.$user_id);
                    if(!$res) die(write(0, '修改失败!'));
                } 
            }
            echo write(1, '修改成功!');
        }else if('all' == $type){
            $user_id = $_GET['user_id'];
            if(!$user_id) die(write(0, 'user_id错误'));
            $sql = "select * from `cart` where `user_id` = $user_id";
            $res = mysql::getAll($sql);
            if(!$res) die(write(1, '无数据'));
            echo write(1, '获取成功', $res);
        }else if('del' == $type){
            $cart_ids = $_POST['cart_ids'];
            if(!$cart_ids) die(write(0, 'cart_ids错误'));
            $sql = "delete from `cart` where `cart_id` in ($cart_ids)";
            $res = mysql::query($sql);
            if(!$res) die(write(1, '删除失败'));
            echo write(1, '删除成功', $res);
        }else{
            $user_id = $_GET['user_id'];
            if(!$user_id) die(write(0, 'user_id错误'));
            $sql = "select * from `cart` c inner join `goods` g on c.`goods_id`= g.`goods_id`  where `user_id` = $user_id";
            $res = mysql::getAll($sql);
            if(!$res) die(write(1, '无数据'));
            echo write(1, '获取成功', $res);
        }
    }catch(\Throwable $t){
        echo write(0, ''.$t);
    }finally{
         mysql::close();
    }
    function write($code, $msg, $data=[]){
        $rd = array(
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        );
        return json_encode($rd, JSON_UNESCAPED_UNICODE);
    }
?>